<?php

class quoteRefreshTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'propel'),
      // add your own options here
      new sfCommandOption('limit', null, sfCommandOption::PARAMETER_REQUIRED, 'Limit of authors on which to refresh quotes', '1'),
      new sfCommandOption('count', null, sfCommandOption::PARAMETER_NONE, 'Count remaining authors to refresh'),
    ));

    $this->namespace        = 'quote';
    $this->name             = 'refresh';
    $this->briefDescription = 'Delete duplicate quotes';
    $this->detailedDescription = <<<EOF
The [quoteRefresh|INFO] task does things.
Call it with:

  [php symfony quoteRefresh|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    $limit = $options['limit'];

    mysql_connect('localhost', 'root', '123456');
    mysql_select_db('quotes');

    $total_start = $this->getMicroTime();
    $authors_refreshed = 0;
    $total_quotes_erased = 0;

    if($options['count'])
    {
      $query = "select a.id as id from author a join refresh r on a.id = r.author_id where r.status = 0 ";
      $result = mysql_query($query);
      $count = mysql_num_rows($result);
      $this->logSection('count  >>', $count.' remaining authors to refresh');
      exit;
    }

    $query = "select a.id as id from author a join refresh r on a.id = r.author_id where r.status = 0 order by a.id limit $limit";
    $ids = array();
    $result = mysql_query($query);
    while($row = mysql_fetch_array($result))
    {
      $ids[] = $row['id'];
    }

    $authors = AuthorQuery::create()
      ->filterById($ids)
      ->find();

    foreach($authors as $author)
    {
      $starttime = $this->getMicroTime();

      $author_id = $author->getId();
      $erased = $this->deleteDuplicatesForAuthorId($author_id);
      $this->updateRefreshForId($author_id);

      $endtime = $this->getMicroTime();
      $totaltime = ($endtime - $starttime);
      $measure = 'seconds';
      if($totaltime > 60)
      {
        $totaltime/=60;
        $measure = 'minutes';
      }
      $authors_refreshed++;
      $total_quotes_erased += $erased;
      $this->logSection('author  >>', $author_id.'. '. $author->getName().' refreshed in '.round($totaltime, 2).' '.$measure." and erased $erased quotes");
    }

    $total_end = $this->getMicroTime();
    $totaltime = ($total_end - $total_start);
    $measure = 'seconds';
    if($totaltime > 60)
    {
      $totaltime/=60;
      $measure = 'minutes';
    }
    $this->logSection('summary  >>', $authors_refreshed.' authors refreshed in '.round($totaltime, 2).' '.$measure." (finished at ".date("H:i:s").") and erased $total_quotes_erased quotes");
  }

  protected function updateRefreshForId($id)
  {
    $query = "update refresh set status = 1 where author_id = $id";
    mysql_query($query);
  }

  protected function deleteDuplicatesForAuthorId($author_id)
  {
    $quotes_erased = 0;
    $query = "SELECT COUNT( * ) AS count, author_id, content, id
      FROM quote
      WHERE author_id = $author_id
      GROUP BY content";

    $result = mysql_query($query);
    while($row = mysql_fetch_array($result))
    {
      $quote_id = $row['id'];
      $quotes_deleted = QuoteQuery::create()
        ->filterByContent($row['content'])
        ->filterById($quote_id, Criteria::NOT_EQUAL)
        ->delete();
      $quotes_erased += $quotes_deleted;
    }

    return $quotes_erased;
  }


  protected function getMicroTime()
  {
    $mtime = microtime();
    $mtime = explode(" ",$mtime);
    $mtime = $mtime[1] + $mtime[0];

    return $mtime;
  }
}
